#include <tossim.h>
#include <stdlib.h>

int main()
{
	FILE *Meyer;
	FILE *Topo;

	int i, j;
	int src, dst;
	double gain;
	int noise;
	double total_current;

	Tossim* t = new Tossim(NULL);
	t->init();

	Radio* r = t->radio();

	Meyer = fopen("meyer-heavy.txt", "r");
	Topo = fopen("topo.txt", "r");

	t->addChannel("Boot", stdout);
	t->addChannel("MultiApps", stdout);
	t->addChannel("SimMoteP", stdout);
	t->addChannel("SimMainP", stdout);
//	t->addChannel("Gain", stdout);
//	t->addChannel("Binary", stdout);
//	t->addChannel("CpmModelC", stdout);


printf("Before Network conf\n");

	// Network Configuration with topo.txt
	while(fscanf(Topo, "%d %d %lf", &src, &dst, &gain) != EOF)
	{
		r->add(src, dst, gain);
	}
	fclose(Topo);

	// Set Boottime
	for(i = 1; i < 4; i++) /* 999 nodes */
	{
printf("%d %d set Node\n", i, (i%2+1));
                t->setNode(i, (i%2+1), i*100);
		Mote* m = t->getNode(i);
		m->bootAtTime(5000003*i + 1);
printf("set boot time\n");
	}


	/* Simulate the RF noise and interference */
	/* To configure the Closest Pattern Matching (CPM), feed the entire noise trace and generate a statistical model */


	while(fscanf(Meyer, "%d", &noise) != EOF)
	{
		for(i = 1; i < 4; i++)
		{
			Mote* m = t->getNode(i);
			m->addNoiseTraceReading(noise);
		}
	}
	fclose(Meyer);
printf("Noise Setting\n");


	for(i = 1; i < 4; i++) /* 999 nodes */
	{
		Mote* m = t->getNode(i);
		m->createNoiseModel();
	}

printf("create Noise Model\n");

	for(i = 1; i <= 100; i++)
	{
		while(t->runNextEventSec(i));
              
		for(j = 1; j < 4; j++)
		{
			total_current = t->getCurrentSec(j,0) + t->getCurrentSec(j, 1) + t->getCurrentSec(j, 2);

			printf("\nMote %d, Battery %.3lf TOTAL CURRENT %10.3lf: cpu %10.3lf radio %10.3lf led %10.3lf", j, t->getBatterySec(j, i), total_current, t->getCurrentSec(j, 0), t->getCurrentSec(j, 1), t->getCurrentSec(j, 2) );
		}
                getchar();
	}
	
	return(0);
}
